from django.shortcuts import HttpResponse,render,redirect
from app01 import models

from app01.utils.pagination import Pagination
from app01.utils.bootstrapmodel import BootStrapModelForm
def adminuser_list(request):
    '''管理员列表'''
    #搜索的功能
    data_dic={}
    search_data=request.GET.get('q','')
    if search_data:
        data_dic={
            'username__contains':search_data
        }
    #根据搜索条件去数据库获取
    queryset=models.Adminuser.objects.filter(**data_dic)
    #分页的功能
    page_object=Pagination(request,queryset)
    context={
        'queryset':page_object.page_queryset,
        'search_data':search_data,
        'page_string':page_object.html()
    }
    return render(request,'admin_list.html',context)
from django import forms


class AdminuserModelForm(BootStrapModelForm):
    confirm_password = forms.CharField(
        label="确认密码",
        widget=forms.PasswordInput
    )

    class Meta:
        model = models.Adminuser
        fields = ['username', 'password', 'confirm_password']
        widgets = {
            'password': forms.PasswordInput
        }

    def clean_confirm_password(self):
        password = self.cleaned_data.get('password')
        confirm_password = self.cleaned_data.get('confirm_password')

        if password != confirm_password:
            raise forms.ValidationError("两次密码输入不一致")
        return confirm_password

    def save(self, commit=True):
        user = super().save(commit=False)
        user.set_password(self.cleaned_data['password'])  # 加密密码
        if commit:
            user.save()
        return user


def adminuser_add(request):
    '''添加管理员'''
    title = "新建管理员"

    if request.method == 'GET':
        form = AdminuserModelForm()
        return render(request, 'Admin_add.html', {'form': form, 'title': title})

    form = AdminuserModelForm(data=request.POST)
    if form.is_valid():
        form.save()  # 现在会加密密码
        return redirect('/admin/list/')

    return render(request, 'Admin_add.html', {'form': form, 'title': title})

